package com.xiaoma.future;

import com.google.common.collect.Lists;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureListDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Random random=new Random();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("future start at "+dateFormat.format(new Date()));

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ArrayList<Future<String>> taskList = Lists.newArrayList();

        for (int i = 0; i < 3; i++) {
            taskList.add(executorService.submit(()->{
               int cnt= random.nextInt(5000);
                String name = Thread.currentThread().getName();
                System.out.println(name+ "线程开始执行时间"+ dateFormat.format(new Date()));
                System.out.println(name+ "睡眠"+cnt+"ms");
                Thread.sleep(cnt);
                return name;
            }));
        }

        for (Future<String> task:taskList){
            System.out.println(task.get()+"执行时间是"+dateFormat.format(new Date()));
        }

    }
}
